package com.le.sarrs.service.impl;

import com.le.sarrs.cms.CmsHandler;
import com.le.sarrs.dao.IDao;
import com.le.sarrs.service.IRecService;
import com.le.sarrs.service.SarrsService;
import com.le.sarrs.util.StringUtil;
import com.le.sarrs.util.Utils;
import com.le.sarrs.web.model.RecommendParam;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class HoneyComRecService implements IRecService {

    private static final Logger log = LoggerFactory.getLogger(HoneyComRecService.class);

    @Qualifier("honeycombDao")
    @Autowired
    private IDao honeycomDao;


    @Override
    public JSONObject queryRecommendation(RecommendParam params) {
        long start = System.currentTimeMillis();

        String lc = params.getLc();
        String cid = params.getCid();
        String ip = params.getLocation().getClientIp();
        String region = params.getLocation().getRegion();
        String from = params.getFrom();

        JSONObject json = new JSONObject();
        // leview
        log.info("client request ip:" + ip + ",and region:" + region);
        String reid = "";

        if ("LeJianMovie".equals(params.getVersiontype())) { // 大陆影视版
            try {
                String result = honeycomDao.getRec(params);

                log.debug(params + "==" + result);

                json = JSONObject.fromObject(result);
                reid = json.optString("reid");
                List<Map<String, Object>> recList = SarrsService.getRecList(json, params.getVersiontype(), !(StringUtil.isNotBlank(from) && "auto_backseat,auto".contains(from)));

                json.put("rec", recList);
                json.put("suggestTags", json.opt("suggest_tags"));
                json.remove("suggest_tags");

                // add置顶信息
                if ("0,hot".contains(cid)) {
                    JSONObject jsonObject = JSONObject.fromObject(CmsHandler.getData(params.getVersiontype(), 1));
                    if (jsonObject != null && jsonObject.optInt("status") == 1) {
                        JSONObject tmp = jsonObject.optJSONObject("data");
                        json.put("top", tmp.optJSONArray("records"));
                    }
                }
            } catch (Exception e) {
                log.error("parse " + " error!reid=" + json.optString("reid"), e);
            }
            log.warn(Utils.log("sarrs_api_rec", System.currentTimeMillis()
                    - start, lc, ip, params.toString(), reid));
        }

        return json;
    }

}